import {
    getPeopleSex, getPeopleHobby, getPeopleCareer, getPeopleRegister,
    getMemberWeekRegister, getProvince, getModel, getDeviceRegion, getMemberRegion
} from '@/base/api/MemberApi';
import { ModelData, ProvinceData } from '@/base/model/Label';
import { calculateTrendLine } from "@/base/util/Dates";
export class DataBloc {
    peopleSex: any = [
        {
            "sex": "2",
            "percentage": 0,
            "num": 0
        },
        {
            "num": 0,
            "sex": "0",
            "percentage": 0
        },
        {
            "num": 0,
            "sex": "1",
            "percentage": 0
        }
    ]
    peopleHobby: any
    peopleCareer: any
    optionsHobby: any = {
        color: [
            '#5470C6', '#91CC75', '#FAC858', '#EE6666', '#6EC1E1', '#3BA272',
            '#FC8452', '#9A60B4', '#EA7CCC', '#ЗАА1FF', '#00C8A0', '#E0D738',
            '#957EDC', '#107EF3', '#D6941A'
        ],
        title: {
            text: '兴趣分布情况',
            left: 'center',
        },
        legend: {
            top: 'bottom'
        },
        series: [
            {
                name: 'Nightingale Chart',
                type: 'pie',
                radius: [15, 100],
                center: ['50%', '50%'],
                roseType: 'area',
                itemStyle: {
                    borderRadius: 8
                },
                data: [

                ]
            }
        ]
    }
    optionsCareer: any = {
        color: [
            '#5470C6', '#91CC75', '#FAC858', '#EE6666', '#6EC1E1', '#3BA272',
            '#FC8452', '#9A60B4', '#EA7CCC', '#ЗАА1FF', '#00C8A0', '#E0D738',
            '#957EDC', '#107EF3', '#D6941A'
        ],
        title: {
            text: '职业分布情况',
            left: 'center',
        },
        legend: {
            top: 'bottom'
        },
        series: [
            {
                name: 'Nightingale Chart',
                type: 'pie',
                radius: [15, 100],
                center: ['50%', '50%'],
                roseType: 'area',
                itemStyle: {
                    borderRadius: 8
                },
                data: [
                ]
            }
        ]
    }
    startValue = 0
    endValue = 0
    optionsRegister: object = {
        color: ['#2d8cf0', '#91CC75', '#ee656e'],
        title: {
            text: '注册统计',
            left: 'center',
            top: 5
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            feature: {
                dataView: { show: true, readOnly: false },
                restore: { show: true },
                saveAsImage: { show: true }
            }
        },
        legend: {
            bottom: 0,
            data: ['平均线', '数据展示', '趋势线']
        },
        grid: [{ left: '5%', top: '10%', width: '90%', height: '80%' }],
        xAxis: [
            {
                name: '日期',
                type: 'category',
                boundaryGap: false,
            }
        ],
        yAxis: {
            name: '人数',
            type: 'value'
        },
        series: [
            {
                name: '平均线',
                type: 'line',
                data: []
            },
            {
                name: '数据展示',
                type: 'line',
                data: []
            },
            {
                name: '趋势线',
                type: 'line',
                markLine: {
                    animation: true,
                    lineStyle: {
                        type: 'dashed',
                        color: 'red'
                    },
                    data: [
                        [
                            {
                                coord: [0, 0],
                                symbol: 'none'
                            },
                            {
                                coord: [0, 0],
                                symbol: 'none'
                            }
                        ]
                    ]
                }
            },
        ]
    }

    dateRegister = [
        new Date(new Date().getTime() - 6 * 30 * 24 * 60 * 60 * 1000),
        new Date()
    ];
    startValue2 = 0
    endValue2 = 0
    options2: object = {
        color: ['#2d8cf0', '#91CC75', '#ee656e'],
        title: {
            text: '周增长统计',
            left: 'center',
            top: 5
        },
        tooltip: {
            trigger: 'axis'
        },
        toolbox: {
            feature: {
                dataView: { show: true, readOnly: false },
                restore: { show: true },
                saveAsImage: { show: true }
            }
        },
        legend: {
            bottom: 0,
            data: ['平均线', '数据展示', '趋势线']
        },
        grid: [{ left: '5%', top: '10%', width: '90%', height: '80%' }],
        xAxis: [
            {
                name: '周',
                type: 'category',
                boundaryGap: false,
            }
        ],
        yAxis: {
            name: '人数',
            type: 'value'
        },
        series: [
            {
                name: '平均线',
                type: 'line',
                data: []
            },
            {
                name: '数据展示',
                type: 'line',
                data: []
            },
            {
                name: '趋势线',
                type: 'line',
                markLine: {
                    animation: true,
                    lineStyle: {
                        type: 'dashed',
                        color: 'red'
                    },
                    data: [
                        [
                            {
                                coord: [0, 0],
                                symbol: 'none'
                            },
                            {
                                coord: [0, 0],
                                symbol: 'none'
                            }
                        ]
                    ]
                }
            },
        ]
    }
    options5 = {
        title: {
            text: '设备增长统计',
            left: 'center',
            top: 5
        },
        dataZoom: {
            show: true,
            realtime: true,
            y: 36,
            height: 20,
            start: 0,
            end: 20
        },
        color: '#2d8cf0',
        xAxis: {
            type: 'category',
            data: [],
            axisLabel: { interval: 0, rotate: 30 },
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [],
                type: 'bar',
                label: {
                    show: true,
                    position: 'inside'
                },
            }
        ]
    };
    options6 = {
        title: {
            text: '会员增长统计',
            left: 'center',
            top: 5
        },
        dataZoom: {
            show: true,
            realtime: true,
            y: 36,
            height: 20,
            start: 0,
            end: 20
        },
        color: '#2d8cf0',
        xAxis: {
            type: 'category',
            data: [],
            axisLabel: { interval: 0, rotate: 30 },
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [],
                type: 'bar',
                label: {
                    show: true,
                    position: 'inside'
                },
            }
        ]
    };

    date2 = [
        // new Date(new Date().getTime()-12*30*24*60*60*1000),
        new Date(new Date().getTime() - 12 * 30 * 24 * 60 * 60 * 1000),
        new Date()
    ];
    date3 = [
        // new Date(new Date().getTime()-12*30*24*60*60*1000),
        new Date(new Date().getTime() - 30 * 24 * 60 * 60 * 1000),
        new Date()
    ];
    region: string = '全部地区';//地区
    provinceList: Array<ProvinceData> = [];
    modelList: any = [];
    province: string = '';//省份
    province3: string = '';//省份
    range3: number = 0;
    modelId: number = 0;//按摩椅型号
    txt1: string = '';
    getPeopleSex() {
        return getPeopleSex().then((res) => {
            this.peopleSex = res.data
        })
    }
    getPeopleHobby() {
        return getPeopleHobby().then((res) => {
            this.optionsHobby['series'][0]['data'] = res.data.map((item) => ({
                'name': `${item.labelname} ${item.count}`,
                'value': item.count,
            }))
        })
    }
    getPeopleCareer() {
        return getPeopleCareer().then((res) => {
            this.optionsCareer['series'][0]['data'] = res.data.map((item) => ({
                'name': `${item.labelname} ${item.count}`,
                'value': item.count,
            }))
        })
    }
    // 获取省份
    getProvince() {
        return getProvince().then((res) => {
            this.provinceList = res.data;
        })
    }
    getModel() {
        return getModel().then((res) => {
            if (res.data.length > 0) {
                res.data.forEach((item) => {
                    if (item.id == 1324949759328288) this.modelList = item.model;
                })
            }

        })
    }
    async getPeopleRegister() {
        let startTime: any = this.dateRegister[0].getTime()
        let endTime: any = this.dateRegister[1].getTime()
        return await getPeopleRegister({
            startTime,
            endTime
        }).then((res) => {
            // console.log(res.data);return;
            if (res.data.length <= 0) return
            const dataList: any = []
            const dataAvg: any = []
            // 1. 提取num字段为一个数组
            const nums = res.data.map(item => item.num);
            // 2. 求和
            const sum = nums.reduce((total, cur) => total + cur, 0);
            // 3. 求平均值
            const avg = Math.ceil(sum / nums.length);
            res.data.map((item) => {
                dataList.push([item.month, item.num])
                dataAvg.push([item.month, avg])
            })
            const trendLine = calculateTrendLine(res.data)
            // console.log('斜率:', trendLine.slope);
            // console.log('截距:', trendLine.intercept);
            // console.log('起始点值:', trendLine.startValue);
            // console.log('结束点值:', trendLine.endValue);
            this.startValue = trendLine.startValue
            this.endValue = trendLine.endValue
            this.optionsRegister['series'][0]['data'] = dataAvg
            this.optionsRegister['series'][1]['data'] = dataList
            this.optionsRegister['series'][2]['markLine']['data'][0][0]['coord'][0] = dataList[0][0]
            this.optionsRegister['series'][2]['markLine']['data'][0][0]['coord'][1] = this.startValue
            this.optionsRegister['series'][2]['markLine']['data'][0][1]['coord'][0] = dataList[dataList.length - 1][0]
            this.optionsRegister['series'][2]['markLine']['data'][0][1]['coord'][1] = this.endValue
            console.log(dataList, trendLine, this.optionsRegister)
        })
    }
    async getMemberWeekRegister() {
        let startTime: any = this.date2[0].getTime()
        let endTime: any = this.date2[1].getTime()
        let region = this.region == '全部地区' ? '' : this.region
        let province = this.province
        let modelId = this.modelId
        return await getMemberWeekRegister({
            startTime,
            endTime,
            region,
            province,
            modelId
        }).then((res) => {
            if (res.data.length <= 8) {
                this.options2['series'][0]['data'] = [0, 0, 0, 0, 0, 0, 0]
                this.options2['series'][1]['data'] = [0, 0, 0, 0, 0, 0, 0]
                this.options2['series'][2]['markLine']['data'][0][0]['coord'][0] = 0
                this.options2['series'][2]['markLine']['data'][0][0]['coord'][1] = 0
                this.options2['series'][2]['markLine']['data'][0][1]['coord'][0] = 0
                this.options2['series'][2]['markLine']['data'][0][1]['coord'][1] = 0
                this.txt1 = ``
            } else {

                const dataList: any = []
                const dataAvg: any = []
                const modifiedData: any = []
                // 1. 提取num字段为一个数组
                const nums = res.data.map(item => item.count);
                // 2. 求和
                const sum = nums.reduce((total, cur) => total + cur, 0);
                // 3. 求平均值
                const avg = Math.ceil(sum / nums.length);

                res.data.map((item) => {
                    const weekNumber = this.getWeekNumber(item.weekend);
                    dataList.push([`${weekNumber}周`, item.count])
                    dataAvg.push([`${weekNumber}周`, avg])
                    modifiedData.push({
                        month: item.weekstart, // 提取日期中的月份
                        num: item.count // 将字符串转换成整型
                    })
                })


                const trendLine = calculateTrendLine(modifiedData)
                // console.log('斜率:', trendLine.slope);
                // console.log('截距:', trendLine.intercept);
                // console.log('起始点值:', trendLine.startValue);
                // console.log('结束点值:', trendLine.endValue);
                this.startValue2 = trendLine.startValue
                this.endValue2 = trendLine.endValue
                this.options2['series'][0]['data'] = dataAvg
                this.options2['series'][1]['data'] = dataList
                this.options2['series'][2]['markLine']['data'][0][0]['coord'][0] = dataList[0][0]
                this.options2['series'][2]['markLine']['data'][0][0]['coord'][1] = this.startValue2
                this.options2['series'][2]['markLine']['data'][0][1]['coord'][0] = dataList[dataList.length - 1][0]
                this.options2['series'][2]['markLine']['data'][0][1]['coord'][1] = this.endValue2
                console.log('dataList', `${Number(dataList[dataList.length - 2][1]) > Number(dataList[dataList.length - 3][1])}`)
                let txt2 = Number(dataList[dataList.length - 2][1]) > Number(dataList[dataList.length - 3][1]) ? '上升' : '下降'
                const zhouhuanbi = dataList[dataList.length - 2][1] == 0 ? `周环比 0%` : `周环比${((dataList[dataList.length - 2][1] - dataList[dataList.length - 3][1]) / dataList[dataList.length - 2][1] * 100).toFixed(2) || 0}%`


                const qushi = this.endValue2 > this.startValue2 ? '上升趋势' : (this.endValue2 == this.startValue2 ? '平稳趋势' : '下降趋势')
                this.txt1 = `总人数${Math.ceil(this.peopleSex[0].num / (this.peopleSex[0].percentage / 100))}人，${dataList[dataList.length - 2][0]}新增${dataList[dataList.length - 2][1]}人，相比${dataList[dataList.length - 3][0]}${txt2}${Math.abs(dataList[dataList.length - 2][1] - dataList[dataList.length - 3][1])}人，${zhouhuanbi}，平均周增长人数${avg}人，总体呈${qushi}`
                if (avg == 0) {
                    this.txt1 = '';
                }
            }

        })
    }

    getWeekNumber(dateString: string) {
        const date: any = new Date(dateString);
        date.setHours(0, 0, 0, 0);

        const januaryFirst: any = new Date(date.getFullYear(), 0, 1);
        const daysOffset = januaryFirst.getDay() === 0 ? 1 : 8 - januaryFirst.getDay();

        const daysDiff = Math.floor((date - januaryFirst) / (24 * 60 * 60 * 1000)) + 1;
        const weekNumber = Math.ceil((daysDiff - daysOffset) / 7) + 1;

        return date.getFullYear() + '/第' + weekNumber;
    };

    async getDeviceRegion() {
        let createBegin: any = this.formattedDate(this.date3[0])
        let createEnd: any = this.formattedDate(this.date3[1])
        let province = this.province3
        let range=this.range3
        return await getDeviceRegion({
            createBegin,
            createEnd,
            province,
            range
        }).then((res) => {
            let xAxis: any = [];
            let series: any = [];
            res.data.map((item) => {
                if (item.count > 0) {
                    xAxis.push(item.area)
                    series.push(item.count)
                }
            })
            this.options5.xAxis.data = xAxis
            this.options5.series[0].data = series
            if(this.range3==0){
                this.options5.dataZoom.end=100
            }else{
                this.options5.dataZoom.end=20
            }
        })
    }

    async getMemberRegion() {
        let createBegin: any = this.formattedDate(this.date3[0])
        let createEnd: any = this.formattedDate(this.date3[1])
        let province = this.province
        let range=this.range3
        return await getMemberRegion({
            createBegin,
            createEnd,
            province,
            range
        }).then((res) => {
            let xAxis: any = [];
            let series: any = [];
            res.data.map((item, index) => {
                if (item.count > 0) {
                    xAxis.push(item.area)
                    series.push(item.count)
                }
            })
            this.options6.xAxis.data = xAxis
            this.options6.series[0].data = series
            if(this.range3==0){
                this.options6.dataZoom.end=100
            }else{
                this.options6.dataZoom.end=20
            }
        })
    }

    formattedDate(date) {
        const year = date.getFullYear(); // 年份
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份（注意+1，并用padStart添加0）
        const day = String(date.getDate()).padStart(2, '0'); // 天
        const hours = String(date.getHours()).padStart(2, '0'); // 小时
        const minutes = String(date.getMinutes()).padStart(2, '0'); // 分钟
        const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }


}
